<template src="./workOrder.html"></template>

<script>
import Bus from '@/utils/event_bus'
import GMenuItem from '@/components/common/g-menu-item'
import GButton from '@/components/common/g-button'
import workOrderList from './workOrderList'
import { appNameMapping } from '@/config/config'
import { appsInUse } from '@/config/config'
import {project as projectApi} from '@/api'
import {app as appApi} from '@/api'
import config from '@/config/newConfig.js'
import debounce from 'lodash.debounce'
import { setTimeout } from 'timers';
export default {
    name: 'workOrder',
    data () {
        return {
            curWorkOrderStep: 1,
            curProblemCategory: "",
            
            selected: 'list',
            selectedName:'我的工单',
            activeNames:"",
            activeNames2:"",
            
            loading:false,

           fileList:[],
           appList: {
                name: '数据加工',
                submenu: [{
                        "name": "我的加工",
                        "key": "list",
                        "icon": "project2",
                        "count": 148
                    },
                    {
                        "name": "提交处理",
                        "key": "submit",
                        "icon": "project2",
                        "count": 148
                    }
                ]
            },
            tableData: [],
            curPage: 1,
            total: 0,
            
            searchInput:"",
            formData:{
                // sheetId:"",
                sheetType: "",
                description: "",
                resFrom: "1",
                fileList: [],

                downLoadDataUuid: "",
                dataUsage: "",
                data_secret: "",
                targetFormat: "",
                coordTarget: "",
                coordOriginal: "",
                contactsName: "",
                mobile: ""
            },
            workOrderStatusList:[],
            detailDialogVisible: false,
            detailFormData:{
                sheetId: "",
                sheetType:"",
                sheetTypeName: "",
                mobile: "",
                sheetStatusName: "",
                
                downLoadDataUuid:"",
                dataUsage: "",
                dataSecret: "",
                targetFormat: "",
                description: "",
                coordTarget: "",
                coordOriginal: "",
                attachFile:[],
                downLoadFile:null
            }  
        }
    },
    activated () {
        //this.$emit( 'on-view-load' );
    },
    beforeRouteLeave ( to, from, next ) {
        // this.$destroy();
        next();
    },
    mounted () {
        // const vm = this;
        // Bus.$emit('on-submenu-change', '');
        // this.getMyApps();
        // await this.init();
        let path = this.$router.currentRoute.path;
        let paths = path.split('/');
        // await this.switchProjectType(paths[2]);
        // this.isMounted = true;
        
        this.$emit( 'on-view-load' );
        let name = this.getAppListByKey(paths[2]).name;
        Bus.$emit('on-submenu-change', name);

        this.query();
        this.statWorkOrder();

        window.addEventListener('resize', debounce(()=>{
            this.adjustWorkorderHeight();
        },200));
    },
    methods: {
        getAppListByKey (key) {
            let apps = this.appList.submenu;
            let app = apps.filter((n) => {
                return n.key === key;
            });
            return app[0];
        },
        switchNav(key,from){
            if (key === this.selected) 
                return;
                this.selected = key;
            let apps = this.appList.submenu;
            let app = apps.find((n) => {
                return n.key === key;
            });
            this.selectedName = app.name;
            if(from == 'add'){
                this.statWorkOrder();
                this.query();
            }
        },
        queryDetail(row){
            // console.log(row);
            this.detailDialogVisible = true;
            let url = `${config.api}/workorder/query/${row.sheetId}`;
            this.$root.$http.get(url).then((response)=>{
                // console.log(response);
                let downLoadFile = response.data.data.downLoadFile;
                if(downLoadFile){
                    downLoadFile.url=`${config.api}/file/download/${downLoadFile.fileId}`;
                }
                this.detailFormData = response.data.data;
            });
        },
        deleteRow(index, rows) {
            this.$confirm('确定要删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteWorkOrder(rows, index);
                
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
        },
        query(type){
            if(type != 'more'){
                this.curPage = 1;
            }
            let params={};
            if(this.searchInput!=""){
                params.title = this.searchInput;
            }
            let url = `${config.api}/workorder/query?rows=8&page=${this.curPage}&order=DESC`;
            this.$root.$http.get(url,{
                params:params
            })
            .then((response)=>{
                //console.log(response);
                this.tableData = response.data.data;
                this.total = response.data.total;
            });
        },
        statWorkOrder(){
            this.$root.$http.get(`${config.api}/workorder/status/stat`)
            .then((response)=>{
                // console.log(response);
                this.workOrderStatusList = response.data.data;
                
            });
        },
        deleteWorkOrder(rows, index){
            let sheetId = rows[index].sheetId;
            this.$root.$http.get(`${config.api}/workorder/delete/${sheetId}`)
            .then((response)=>{
                // console.log(response);
                if(response.data.success){
                    rows.splice(index, 1);
                    this.$message.success('删除成功！');
                }else{
                    this.$message.error('删除失败！');
                }
                
            });
        },
        handleWorkOrderStep(step, event){
            let list = this.$el.querySelectorAll('.step-item');
            for(let item of list){
                item.classList.remove('active');
            }
            let currentTarget = event.currentTarget;
            currentTarget.parentNode.classList.add('active');
            if(step == 1){
               this.curWorkOrderStep = 1;
            }else if(step == 2){
                
            }
           
        },
        handleWorkOrder(name, index){
            this.formData.sheetType = index;
            this.curWorkOrderStep = 2;
            this.curProblemCategory = name;
            this.$el.querySelector('.step1-item').classList.remove('active');
            this.$el.querySelector('.step2-item').classList.add('active');
            this.$nextTick(()=>{
                this.adjustWorkorderHeight();
            });
            
            
        },
        adjustWorkorderHeight(){
            let dom = document.querySelector('.make-workorder');
            if(!dom){
                return;
            }
            let height = dom.offsetHeight;
            // console.log(height);
            // return;
            document.querySelector('.make-workorder-scrollbar').style.height = height-100+'px';
            
        },
        handleUploadChange(file, fileList){
            this.formData.fileList = fileList;
        },
        handleSubmit(){
            if(this.formData.sheetType == 2 && this.formData.downLoadDataUuid==""){
                this.$message.error('请输入数据ID！');
                return;
            }
            if(this.formData.dataUsage==""){
                this.$message.error('请输入数据用途！');
                return;
            }
            if(this.formData.sheetType == 1 && this.formData.dataSecret==""){
                this.$message.error('请选择数据涉密！');
                return;
            }
            // console.log(this.formData.data_secret);
            
            
            if(this.formData.targetFormat==""){
                this.$message.error('请选择目标格式！');
                return;
            }
            if(this.formData.description==""){
                this.$message.error('请输入问题描述！');
                return;
            }
            if(this.formData.sheetType==2){
                if(this.formData.coordTarget==""){
                    this.$message.error('请选择输出坐标！');
                    return;
                }
            }else if(this.formData.sheetType==1){
                if(this.formData.coordOriginal==""){
                    this.$message.error('请选择原始坐标！');
                    return;
                }
                if(this.formData.coordTarget==""){
                    this.$message.error('请选择目标坐标！');
                    return;
                }
            }
            
            if(this.formData.contactsName==""){
                this.$message.error('请输入联系人！');
                return;
            }
            if(this.formData.mobile==""){
                this.$message.error('请输入联系电话！');
                return;
            }
            if(!/^[0-9]+$/.test(this.formData.mobile)){
                this.$message.error('联系电话只能为数字！');
                return;
            }
            if(this.formData.fileList.length<=0){
                this.$message.error('请上传附件！');
                return;
            }
            let fd = new window.FormData();
            fd.append('sheetType', this.formData.sheetType);
            fd.append('dataUsage', this.formData.dataUsage);
            
            fd.append('targetFormat', this.formData.targetFormat);
            fd.append('description', this.formData.description);
            if(this.formData.sheetType==2){
               fd.append('downLoadDataUuid', this.formData.downLoadDataUuid); 
               fd.append('coordTarget', this.formData.coordTarget);
            }else if(this.formData.sheetType==1){
                let dataSecret = 0;
                if(this.formData.dataSecret == '是'){
                    dataSecret = 1;
                }
               fd.append('dataSecret', dataSecret);
               fd.append('coordTarget', this.formData.coordTarget);
               fd.append('coordOriginal', this.formData.coordOriginal);
            }
            fd.append('contactsName', this.formData.contactsName);
            fd.append('mobile', this.formData.mobile);

            fd.append('resFrom', this.formData.resFrom);
            // console.log(this.formData.fileList);
            
            this.formData.fileList.forEach((file)=>{
                fd.append('dataFile', file.raw);
            });
            let url = `${config.api}/workorder/add`;
            this.$root.$http.post(url, fd,{
                headers:{
                    'Content-Type': 'multipart/form-data'
                }
            }).then((response)=>{
                // console.log(response);
                if(response.data.success){
                    this.$message.success('提交成功！');
                    this.curWorkOrderStep = 1;
                    
                    //清空
                    this.formData = {
                        sheetType: "",
                        description: "",
                        resFrom: "1",
                        fileList: [],

                        downLoadDataUuid:"",
                        dataUsage: "",
                        dataSecret: "",
                        targetFormat: "",
                        coordTarget: "",
                        coordOriginal: "",
                        contactsName: "",
                        mobile: ""
                    };
                    
                    this.switchNav('list', 'add');
                }else{
                    this.$message.error('提交失败！');
                }
            });
        },
        handleLoadMore(page){
            if(this.curPage != page){
                this.curPage = page;      
                
                this.query('more');
            }
        },
        handleSearchInputChange(){
            this.query();
        },
        handleDetailClose(){
            console.log(1);
            
        },
        handlePhoneValid(){
            // console.log(11111);
            
        }
    },
    components: {
        GMenuItem,
        GButton,
        workOrderList
    }
}
</script>

<style src="./workOrder.scss" lang="scss" scoped></style>
